import { Controller, Get, Post, Body, Patch, Param, Delete,UseInterceptors,UploadedFile, Res } from '@nestjs/common';
import { UploadService } from './upload.service';
import {FileInterceptor} from '@nestjs/platform-express'
import type { Response } from 'express'
import { join } from 'path';
import {zip} from 'compressing';

@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}
 
  // 上传图片
  @Post('pic')
  @UseInterceptors(FileInterceptor('file'))
  upload (@UploadedFile() file) {
    if(file) {
      return {
        code: 200,
        url: `http://localhost:3000/images/${file.filename}`
      }
    }
  }

  // 二进制下载图片
  @Get('exportPic')
  exportPic(@Res() res) {
    const url = join(__dirname, '../images/1703595371306.png');
    res.download(url);
  }

  // stream 文件流的方式下载
  @Get('stream')
  async down (@Res() res: Response) {
    const url = join(__dirname, '../images/1703595371306.png');
    const tarStream  = new zip.Stream()
    await tarStream.addEntry(url)
    res.setHeader('Content-Type', 'application/octet-stream');
    res.setHeader(
      'Content-Disposition',  
      `attachment; filename=xiaoman`,
    );
 
    tarStream.pipe(res)
  }
}